<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= title %></title>

  <script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
  <script src="https://unpkg.com/axios@0.19.0/dist/axios.min.js"></script>
  <link rel="stylesheet" href="/css/upload.css">
</head>
<body>
  <div id="app">
    <h1><%= title %></h1>
    <p>请点击下边按钮，上传 📂文件夹</p>

    <div class="upload-btn-container">
      <div class="project-info" v-if="projectInfo.folderName">
        <div class="row">
          <span class="label">项目名</span>
          <span class="value">
            <input type="text" v-model="projectInfo.folderName">
          </span>
        </div>
      </div>

      <div class="upload-btns"
        :class="{ready: isReady}">
        {{ isReady ? '重新选择文件夹' : '上传文件夹' }}
        <input type="file" multiple webkitdirectory class="upload-file-input"
          @change="onUploadBtnChange">
      </div>
    </div>

    <div class="file-list table" v-show="isReady">
      <table class="file-list-table">
        <tr class="table-headers" v-if="isReady">
          <template v-for="header in fileListHeaders">
            <th>{{ header.label || header.key }}</th>
          </template>
        </tr>
        <template v-for="(item, index) in fileList">
          <file-item :key="index" :item="item" :headers="fileListHeaders"></file-item>
        </template>
      </table>
    </div>

    <div class="table-actions" v-if="isReady">
      <div class="btn-submit" v-if="!uploadSuccess"
        @click="submitUpload">
        确认上传
      </div>
      <div class="btn-submit" v-if="uploadSuccess"
        @click="lookupProject">
        查看项目
      </div>
    </div>

  </div>

  <!-- Vue组件 -->
  <%- include('../vue-component/FileItem.ejs') %>

  <script src="/js/utils.js"></script>
  <script src="/js/folderUpload.js"></script>
  <script src="/js/api/project.js"></script>
  <script src="/js/api/file.js"></script>
  <script>
    function $(selector) {
      return document.querySelector(selector)
    }
    
    const uploadFolderBtn = $('.upload-file-input')

    const _app = new Vue({
      el: '#app',
      data: {
        fileListHeaders: [
          { label: '文件名', key: 'name' },
          { label: '大小', key: 'size' },
          { label: '文件类型', key: 'type' },
          // { label: '相对路径', key: 'path' },
          { label: '上传进度', key: 'uploadProgress' },
        ],
        fileList: [],

        projectInfo: {},

        isReady: false,
        uploadSuccess: false,
      },
      components: {
        FileItem,
      },
      mounted() {
        document.addEventListener('drop', ev => {
          ev.preventDefault()

          console.log(ev)
        })
      },
      methods: {
        onUploadBtnChange(ev) {
          const flist = parseFileList(ev.target.files)
          this.fileList = filterUselessFile(flist)
          this.projectInfo = parseFolderInfo(this.fileList)
          this.isReady = true
          this.uploadSuccess = false
        },
        lookupProject() {
          location.href = '/project/' + this.projectInfo.id
        },
        async submitUpload() {
          const list = this.fileList
          const indexFile = list.find(i => i.name === 'index.html')
          if (indexFile) {
            try {
              // 先创建项目
              const prjData = await CreateProject(this.projectInfo.folderName)
              // console.log('STEP1 先创建项目\n ', prjData)
  
              const otherFiles = list.filter(i => i.name !== 'index.html')
              const projectID = prjData.id
              this.projectInfo.id = projectID
              const uploadedInfoList = []
  
              // console.log('STEP2 获取的项目ID，开始上传文件\n ', projectID)
  
              for (let i = 0; i<otherFiles.length; i++) {
                const fileInfo = otherFiles[i]
                console.log(fileInfo)
                const imgData = await PostUploadFile(fileInfo.file, projectID)
                uploadedInfoList.push({
                  fileInfo: otherFiles[i],
                  imgData,
                })
              }
  
              const htmlJSONInfo = await parseSketchMeasureHTML(indexFile.file)

              const jsonObject = JSON.parse(htmlJSONInfo.content)

              const toReplacePath = uploadedInfoList.reduce((d, item) => {
                const key = 'preview/' + item.imgData.originalname
                const value = item.imgData.url
                d[key] = value
                return d
              }, {})

              console.log('toReplacePath', toReplacePath)
              // 修改图片和其他资源的路径
              jsonObject.artboards.forEach(item => {
                // 查找文件URL
                console.log('TO replaced: ', decodeURIComponent(item.imagePath))

                item.imagePath = toReplacePath[decodeURIComponent(item.imagePath)]

                console.log('replaced: ', item.imagePath)
              })
  
              const jsonUploadInfo = await PostUploadJSON(JSON.stringify(jsonObject))

              const projectInfo = await UpdateProject(projectID, JSON.stringify({
                configJSON: jsonUploadInfo.filename,
                staticFileInfo: uploadedInfoList.map(i => i.imgData),
              }))
  
              console.log('projectInfo', projectInfo)
  
              this.uploadSuccess = true
              alert('上传成功')
            } catch (err) {
              console.log(err)
            }
          } else {
            alert('没有找到Index.html，无法完成上传')
          }
        },
      },
    })
  </script>
</body>
</html>